package org.finesys.common.security.core.service.impl;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.finesys.common.constants.SecurityConstants;
import org.finesys.common.core.exception.BusinessException;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.StrUtil;
import org.finesys.common.security.core.module.AuthUser;
import org.finesys.common.security.core.service.AuthUserService;
import org.finesys.system.api.dto.UserGiteeDto;
import org.finesys.system.api.dto.UserInfo;
import org.finesys.system.api.service.UserGiteeService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 用户详细信息:根据gitee用户ID查询
 */

@AllArgsConstructor
public class AuthUserGiteeServiceImpl implements AuthUserService {

    private UserGiteeService userGiteeService;
//    private final RedisTemplate<String, Object> redisTemplate;
//    private final static Long TIME_OUT = 24L;
//    private final static TimeUnit TIME_UNIT = TimeUnit.HOURS;

    /**
     * 用户名密码登录,如果启用租户，则不能再此进行缓存
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String appId) throws UsernameNotFoundException {
        if (StrUtil.isEmpty(appId)) {
            throw new BusinessException("gitee AppId cannot empty");
        }

//        String key = CacheConstants.USER_DETAILS + appId;
//        redisTemplate.setValueSerializer(RedisSerializer.java());
//        Object object = redisTemplate.opsForValue().get(key);
//        if (object != null) {
//            return (AuthUser) object;
//        }
        UserGiteeDto userGiteeDto = new UserGiteeDto();
        userGiteeDto.setAppId(appId);
        R<UserInfo> userInfo = userGiteeService.info(userGiteeDto);
        UserDetails userDetails = getUserDetails(userInfo);
//        redisTemplate.opsForValue().set(key, userDetails, TIME_OUT, TIME_UNIT);
        return userDetails;
    }

    @Override
    public UserDetails loadUserByAuthUser(AuthUser authUser) {
        return this.loadUserByUsername(authUser.getAppId());
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    public boolean support(String clientId, String grantType) {
        return SecurityConstants.GITEE.equals(grantType);
    }
}
